var Api = require('api.js')
//--------------------------------------------------------请求封装---------------------------------------//
function request(url, params, identity, Methob, success, fail) {
  this.requestLoading(url, params, identity, "", '', Methob, success, fail)
}
// 展示进度条的网络请求
// url:网络请求的url
// params:请求参数,
//identity:是否需要参数key身份认证,1,必须验证，2有则传，不要就3
// message:进度条的提示信息
// success:成功的回调函数
// fail：失败的回调
function requestLoading(url, params, identity, message, Methob, header, success, fail) {
  //let params=params;
  let disidkey='disidkey';
  params.disid=wx.getStorageSync(disidkey);
  //console.log("8998989898");

  wx.showNavigationBarLoading()
  if (message != "") {
    wx.showLoading({
      title: message,
      mask: true
    })
  }
  if (this.get('is_show')) {
    var is_show = this.get('is_show');
    if (is_show == 2) {
      wx.showToast({
        icon: 'none',
        title: '小程序被禁用，请联系管理员',
        duration: 10000
      })
      return;
    }
  }
  switch (identity) {
    case 1:
      if (this.get('key')) {
        params.key = this.get('key');
      } else {
        var pageArr = getCurrentPages();
        var thisPage = pageArr[pageArr.length - 1]
        thisPage.setData({
          register: true
        })
      }
      break;
    case 2:
      if (this.get('key')) {
        params.key = this.get('key');
      }
      break;
  }
  var that = this
  wx.request({
    url: url,
    data: params,
    header: {
      'Content-Type': header != '' ? header : (Methob === 'GET' ? 'application/json' : 'application/x-www-form-urlencoded')
    },
    method: Methob,
    success: function(res) {
      wx.hideNavigationBarLoading()
      if (message != "") {
        wx.hideLoading()
      }
      if (res.statusCode == 200) {

        if (res.data.code == 200) {
          success(res.data.datas)
        } else {
          if (res.data.error) {
            if (res.data.error == '请登录') {
              that.remove('key');
              var pageArr = getCurrentPages();
              var thisPage = pageArr[pageArr.length - 1]
              thisPage.setData({
                register: true
              })
            } else {
              wx.showToast({
                icon: 'none',
                title: res.data.error,
              })
              fail(res.data)
            }
          } else {
            if (res.data.datas.error == '请登录') {
              that.remove('key');
              var pageArr = getCurrentPages();
              var thisPage = pageArr[pageArr.length - 1]
              thisPage.setData({
                register: true
              })
            } else {
              wx.showToast({
                icon: 'none',
                title: res.data.datas.error,
              })
              fail(res.data.datas)
            }
          }
        }
      } else {
        fail()
      }

    },
    fail: function(res) {
      wx.hideNavigationBarLoading()
      if (message != "") {
        wx.hideLoading()
      }
      fail()
    },
    complete: function(res) {

    },
  })
}
//获取用户信息
function getuserinfo(success) {
  var that = this;
  if(that.get('key')){
    that.requestLoading(Api.GET.member_info, { member_id: that.get('member_id') }, 1, '', 'GET', '', function (e) {
      that.put('userinfo', e);
      success(true);
    }, function () {
      wx.showToast({
        title: '网络繁忙，请稍后再试',
        icon: 'none'
      })
    })
  }
  
}

//----------------------------------缓存封装------------------------------------------------//
var dtime = '_deadtime'; //缓存过期时间
function put(k, v, t) { //存入，put(key,value,time)
  wx.setStorageSync(k, v)
  var seconds = parseInt(t);
  if (seconds > 0) {
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000 + seconds;
    wx.setStorageSync(k + dtime, timestamp + "")
  } else {
    wx.removeStorageSync(k + dtime)
  }
}

function get(k, def) { //取出get(key,过期，出错时调用def)
  var deadtime = parseInt(wx.getStorageSync(k + dtime))
  if (deadtime) {
    if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
      if (def) {
        return def;
      } else {
        return;
      }
    }
  }
  var res = wx.getStorageSync(k);
  if (res) {
    return res;
  } else {
    return def;
  }
}

function remove(k) { //清楚指定缓存key
  wx.removeStorageSync(k);
  wx.removeStorageSync(k + dtime);
}

function clear() { //清楚该账号所有缓存
  wx.clearStorageSync();
}
//---------------------------------------------------------地理位置获取-------------------------------------------------//
function setlocation(type, compel, hint, success, fail) { //setlocation(type,有值就是gcj02，默认wgs84, compel，是否强制获取位置, hint强制提示文字,success成功回调,fail失败回调)
  var that = this
  wx.setlocation({ //获取地理位置经纬度
    type: type ? 'gcj02' : 'wgs84',
    success: function(res) {
      success(res)
    },
    fail(res) {
      fail(res)
      if (compel) {
        that.opention(type, compel, hint, success, fail);
      }
    }
  });
}

function opention(type, compel, hint, success, fail) { //强制调用授权方法
  var that = this
  wx.showModal({
    title: '获取位置失败',
    content: hint,
    success(res) {
      if (res.confirm) {
        wx.openSetting({
          success: function(data) {
            if (data.authSetting["scope.userLocation"] === true) {
              wx.showToast({
                title: '授权成功',
                icon: 'success',
                duration: 1000
              })
              that.setlocation(type, compel, hint, success, fail);
              //授权成功之后，再调用获取地理位置
            }
          }
        })
      } else if (res.cancel) {
        that.opention(type, compel, hint, success, fail); //重复调用
      }
    }
  })
}
//获取位置的详细信息，包括城市，省份，街道等等
function locationDetails(optionLocation, success, fail) {
  var that = this
  var QQMapWX = require('qqmap/qqmap-wx.js');
  // 实例化API核心类
  var qqmapsdk = new QQMapWX({
    key: Api.qqmapKey
  });
  qqmapsdk.reverseGeocoder({
    location: optionLocation || '',
    success: function(res) { //成功后的回调

      success(res)
    },
    fail: function(error) {
      console.error(error);
      fail(error)
    },
  })
}

function getCityList(success, fail) {
  var that = this
  var QQMapWX = require('qqmap/qqmap-wx.js');
  var qqmapsdk = new QQMapWX({
    key: Api.qqmapKey
  });
  qqmapsdk.getCityList({
    success: function(res) { //成功后的回调
      success(res.result[1]);
      // console.log('省份数据：', res.result[0]); //打印省份数据
      // console.log('城市数据：', res.result[1]); //打印城市数据

      // console.log('区县数据：', res.result[2]); //打印区县数据
    },
    fail: function(error) {
      fail(error);
    },

  });
}

function formid(e) { //传formid
  var openid = this.get('openID')
  if (e.detail.formId == 'the formId is a mock one') {
    return
  }
  if (openid) {
    var params = {
      openid: openid,
      formid: e.detail.formId
    }
    this.requestLoading(Api.GET.from_id, params, 3, "", '', 'GET', function(e) {
      console.log(e)
    }, function(e) {
      console.error(e)
    })
  }
}
//上传图片的方法
function uploadFileList(url, formData, fileList, success, fail, loadTask) { //图片上传地址，携带参数，上传列表可多可单，成功回调，失败回调，进度反馈，
  var gettype = Object.prototype.toString
  var i = 0
  if (gettype.call(fileList) == '[object Array]') {
    if (fileList.length > 1) {

      upload(url, formData, fileList[i], success, fail, i, loadTask);

    } else {
      upload(url, formData, fileList[0], success, fail, 1, loadTask)
    }
  } else {
    upload(url, formData, fileList, success, fail, 1, loadTask)
  }

  function upload(url, formData, thisFile, success, fail, idx, loadTask) {
    const uploadTask = wx.uploadFile({
      url: url, //仅为示例，非真实的接口地址
      filePath: thisFile.path,
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: formData,
      success(res) {
        console.log(res)
        res = JSON.parse(res.data)
        res.datas.idx = i
        console.log(res.datas)
        success(res.datas)
        if (gettype.call(fileList) == '[object Array]') {
          if (idx < fileList.length - 1) {
            i++
            upload(url, formData, fileList[i], success, fail, i, loadTask);
          }
        }
      },
      fail(ros) {
        wx.showToast({
          icon: 'none',
          title: '第' + (i + 1) + '张照片上传失败' + ros.data.error,
        })
        success(ros)
        res.datas.idx = i
        if (gettype.call(fileList) == '[object Array]') {
          if (idx < fileList.length - 1) {
            i++
            upload(url, formData, fileList[i], success, fail, i, loadTask);
          }
        }
      },
    })

    uploadTask.onProgressUpdate((res) => {
      wx.showToast({
        icon: 'none',
        title: '第' + (i + 1) + '张照片上传中..' + res.progress + '%',
      })
      loadTask({
        idx: (i + 1),
        progress: res.progress
      })
    })
  }
}

function validate_required(field, alerttxt) {
  var value = field;
  if (value == null || value == "" || value == []) {
    wx.showToast({
      title: alerttxt,
      icon: 'none',
    });
    return false
  } else {
    return true
  }

}

function toDecimal2(x) {
  var f = parseFloat(x);
  if (isNaN(f)) {
    return false;
  }
  var f = Math.round(x * 100) / 100;
  var s = f.toString();
  var rs = s.indexOf('.');
  if (rs < 0) {
    rs = s.length;
    s += '.';
  }
  while (s.length <= rs + 2) {
    s += '0';
  }
  return s;
}
/*一维数组对象模糊搜索
  dataList 为一维数组数据结构
  value 为input框的输入值
  type 为指定想要搜索的字段名，array格式 ["name", "number"];
 */
function filterOne(dataList, value, type) {
  var s = dataList.filter(function(item, index, arr) {
    for (let j = 0; j < type.length; j++) {
      if (item[type[j]] != undefined || item[type[j]] != null) {
        if (item[type[j]].indexOf(value) >= 0) {
          return item;
        }
      }
    }
  });
  return s;
}
/*二维数组对象模糊搜索
  dataList 为二维数组数据结构
  value 为input框的输入值
  type 为指定想要搜索的字段名，array格式 ["name", "number"];
  field 为二维数组的字段 比如二维数组字段名为user
 */
function filterData(dataList, value, type, field) {
  var s = dataList.filter(function(item, index, arr) {
    for (let i = 0; i < item[field].length; i++) {
      item[field][i].show = false
      for (let j = 0; j < type.length; j++) {

        //console.log(item[field][i],33355)
        if (item[field][i][type[j]] != undefined || item[field][i][type[j]] != null) {
          if (item[field][i][type[j]].indexOf(value) >= 0) {
            var arr2 = [];
            var s = item[field].filter(function(items, indexs, arrs) {
              if (items[type[j]].indexOf(value) >= 0) {
                // arr2.push(items);
                // return arr2;
                items.show = true;
                //return dataList
              }
            })

            // item.user = s;
            // return item;
          }
        }

      }
    }
  });
  return dataList
  //return s;
}

module.exports = {
  request: request, //请求简写
  requestLoading: requestLoading, //请求复写
  put: put, //存入缓存
  get: get, //取出缓存
  remove: remove, //删除指定缓存
  clear: clear, //清楚所有缓存
  formid: formid, //保存formid
  setlocation: setlocation, //获取位置
  opention: opention, //强行设置
  uploadFileList: uploadFileList, //递归上传文件的方法
  validate_required: validate_required, //验证空值
  toDecimal2: toDecimal2, //保留小数
  locationDetails: locationDetails, //给与地址描述
  getCityList: getCityList, //获取城市
  Searcher: filterData, //前端搜索二维数组
  filterOne: filterOne, //前端搜索一维数组
  getuserinfo: getuserinfo, //获取用户信息
}